<?php

/**
 * lexique actions.
 *
 * @package    explications_informatiques
 * @subpackage lexique
 * @author     Guimezanes Cyrille
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class lexiqueActions extends sfActions
{
  public function executeIndex(sfWebRequest $request)
  {
	$this->letters = "ABCDEFGHIKLMNOPQRSTUVWXYZ1234567890";
	
	if($request->getParameter('letter') && strlen($request->getParameter('letter')) == 1 && preg_match("/".strtoupper($request->getParameter('letter'))."/i",$this->letters))
	{
		$q = Doctrine_Query::create()
		->from('lexiqueMot m')
		->leftJoin('m.SfGuardUserProfile p')
		->leftJoin('m.Lexiquedefinition d')
		->leftJoin('d.Lexiquevote v')
		->leftJoin('d.SfGuardUserProfile p2')
		->leftJoin('p.User')
		->leftJoin('p2.User')
		->where('m.mot like ?',$request->getParameter('letter').'%')
		->andWhere("m.online = ?","1")
		->limit("10");
	}
	elseif($request->getParameter('id'))
	{
      $q = Doctrine_Query::create()
		->from('lexiqueMot m')
		->leftJoin('m.SfGuardUserProfile p')
		->leftJoin('m.Lexiquedefinition d')
		->leftJoin('d.Lexiquevote v')
		->leftJoin('d.SfGuardUserProfile p2')
		->leftJoin('p.User')
		->leftJoin('p2.User')
		->where('m.idlexique_mot = ?',$request->getParameter('id'))
		->andWhere("m.online = ?","1")
		->limit("1");
	}
	else
	{
		$q = Doctrine_Query::create()
		->from('lexiqueMot m')
		->leftJoin('m.SfGuardUserProfile p')
		->leftJoin('m.Lexiquedefinition d')
		->leftJoin('d.Lexiquevote v')
		->leftJoin('d.SfGuardUserProfile p2')
		->leftJoin('p.User')
		->leftJoin('p2.User')
		->where("m.online = ?","1")
		->orderBy('m.idlexique_mot')
		->limit("10");
	}
	
	$this->pager = new sfDoctrinePager(
		'Lexiquemot',
		15//nb résultats par pages
	  );
	if($request->getParameter('id'))
	 $this->params = "id=".$request->getParameter('id');
	 
	elseif($request->getParameter('letter'))
	 $this->params = "letter=".$request->getParameter('letter');
	else
	 $this->params = "";
	 
	$this->pager->setQuery($q);
	  $this->pager->setPage($request->getParameter('page', 1));
	  $this->pager->init();
	$this->lexiquesMot = $this->pager->getResults();	
	
	if (count($this->lexiquesMot) < 3 && $this->getUser()->hasCredential("MOD_LEXIQUE"))
	{
		foreach ($this->lexiquesMot as $lex)
		{
			$lex["view_by_mode"] = "1";
			foreach($this->lexiquesMot[0]["Lexiquedefinition"] as $def)
				$def["view_by_mode"] = "1";
			$lex->save();
		}
	}
	
  }
 
  public function executeVote(sfWebRequest $request)
  {
	 $this->forwardUnless($this->getUser()->isAuthenticated() && $this->getUser()->hasCredential("NOTE_DEF"),"headers","forbidden");
	 $q = Doctrine_Query::create()
	 ->from('lexiqueVote m')
	 ->where('m.id_def = ?',$request['id'])
	 ->andWhere('m.id_client = ?',$this->getUser()->getGuardUser()->getId());
	
	 if($q->count() == 0)
	 {
		  $q = Doctrine_Query::create()
				->select("vote as vote")
				->from('lexiquedefinition')
				->where('idlexique_definition = ?',$request['id']);
		  $vote2 = $q->fetchOne();
		  
		  if($request->getParameter('type') == "plus")
			  $vote2["vote"] = intval($vote2["vote"]) + 1;
		  else
			  $vote2["vote"] = intval($vote2["vote"]) - 1;
		  $vote2->save();
		  $vote = new lexiqueVote();
		  $vote->setIdDef($request->getParameter('id'));
		  $vote->setIdClient($this->getUser()->getGuardUser()->getId());
		  $vote->save();
		  $this->getUser()->setFlash('info','Votre vote à été pris en compte');
		  $this->getUser()->updatePoint(10, "Vote");
			if ($cache = $this->getContext()->getViewCacheManager())
			{
				$cache->remove('lexique/index*');
			}
	 }
	 else
	 {
		 $this->getUser()->setFlash('err','Vous ne pouvez pas/plus voter');
	 }
	 $this->redirect('lexique/index');
	 
  }


  public function executeNew(sfWebRequest $request)
  {
	$this->forwardUnless($this->getUser()->isAuthenticated() && $this->getUser()->hasCredential("AJOUT_MOT"),"headers","forbidden");
    $this->form = new lexiqueMotForm();
  }

  public function executeCreate(sfWebRequest $request)
  {
	$this->forwardUnless($this->getUser()->isAuthenticated() && $this->getUser()->hasCredential("AJOUT_MOT"),"headers","forbidden");
    $this->forwardUnless($request->isMethod(sfRequest::POST),"headers","forbidden");

    $this->form = new lexiqueMotForm();

    $this->processForm($request, $this->form);

    $this->setTemplate('new');
  }

  public function executeEdit(sfWebRequest $request)
  {
	$this->forwardUnless($this->getUser()->isAuthenticated() && $this->getUser()->hasCredential("MOD_LEXIQUE"),"headers","forbidden");
    $this->forward404Unless($lexique_mot = Doctrine_Core::getTable('lexiqueMot')->find(array($request->getParameter('idlexique_mot'))), sprintf('Object lexique_mot does not exist (%s).', $request->getParameter('idlexique_mot')));
    $this->form = new lexiqueMotForm($lexique_mot);
  }

  public function executeUpdate(sfWebRequest $request)
  {
	$this->forwardUnless($this->getUser()->isAuthenticated() && $this->getUser()->hasCredential("MOD_LEXIQUE"),"headers","forbidden");
    $this->forwardUnless($request->isMethod(sfRequest::POST) || $request->isMethod(sfRequest::PUT),"headers","forbidden");
    $this->forward404Unless($lexique_mot = Doctrine_Core::getTable('lexiqueMot')->find(array($request->getParameter('idlexique_mot'))), sprintf('Object lexique_mot does not exist (%s).', $request->getParameter('idlexique_mot')));
    $this->form = new lexiqueMotForm($lexique_mot);

    $this->processForm($request, $this->form);

    $this->setTemplate('edit');
  }

  public function executeDelete(sfWebRequest $request)
  {

	$this->forwardUnless($this->getUser()->isAuthenticated() && $this->getUser()->hasCredential("SUPPR_MOT"),"headers","forbidden");
    $this->forward404Unless($lexique_mot = Doctrine_Core::getTable('lexiquemot')->find(array($request->getParameter('idlexique_mot'))), sprintf('Object lexique_mot does not exist (%s).', $request->getParameter('idlexique_mot')));
    $lexique_mot->getSfGuardUserProfile()->decrPoint(100, "Suppression d'un mot du lexique");
	$lexique_mot->delete();
	$this->getUser()->setFlash("info","Mot et définition(s) supprimés");
    $this->redirect('lexique/index');
	
	sfCoreAutoload::logElem("Suppresion d'un mot id:".$request->getParameter('idlexique_mot'), $this->getUser()->getGuardUser()->getId(), date("Y-m-d h:i:s"));
  }

  protected function processForm(sfWebRequest $request, sfForm $form)
  {
	$this->forwardUnless($this->getUser()->isAuthenticated() && $this->getUser()->hasCredential("AJOUT_MOT"),"headers","forbidden");
    $form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));
    $q = Doctrine_Query::create()
	 ->from('lexiquemot m')
	 ->where('m.mot = ?',strtolower($request["lexique"]["mot"]));
	if ($form->isValid() && 
		(!$this->getUser()->hasAttribute("word_timming") || intval($this->getUser()->getAttribute("word_timming") + 120 < time())))// 2 min entre chaque word)
    {
	  if($q->count() == 0)
	  {	
		  $lexique_mot = new Lexiquemot();
		  $lexique_mot->setMot(strtolower($request["lexique"]["mot"]));
		  $lexique_mot->setAuteur($this->getUser()->getGuardUser()->getId());
		  $lexique_mot->setOnline(0);
		  $lexique_mot->setDateAjout(date("Ymdhis"));
		  $lexique_mot->save();
	  }
	  else
	  {
		  $lexique_mot = $q->fetchOne();
	  }
	  
	  $lexique_definition = new Lexiquedefinition();
	  $lexique_definition->setIdMot($lexique_mot);
	  $lexique_definition->setIdAuteur($this->getUser()->getGuardUser()->getId());
	  $lexique_definition->setDefinition($request["lexique"]["definition"]);
	  $lexique_definition->setVote(0);
	  $lexique_definition->setOnline(1);
	  $lexique_definition->save();
	  
	  if ($cache = $this->getContext()->getViewCacheManager())
		  {
			 $cache->remove('lexique/index*');
			 $cache->remove('headers/modepanel');
			 $cache->remove('main/index');
		  }
	  
	  $this->getUser()->setAttribute("word_timming", time());
	  if($request->getParameter('action') == "create")
	  	$this->getUser()->setFlash("info","Mot et définition ajoutés");
	  else
	  	$this->getUser()->setFlash("info","Mot et définition modifiés");
	  $this->getUser()->updatePoint(90, "Ajout d'un mot au lexique");
      $this->redirect('search/lexique?id='.$lexique_mot->getIdlexiqueMot());
    }
	elseif($this->getUser()->hasAttribute("com_timming"))
	{
		$this->getUser()->setFlash("err","Vous devez attendre 2 mins entre chaque commentaire");
		$this->redirect('search/lexique?id='.$lexique_mot->getIdlexiqueMot());
	}
  }
  public function executeRss(sfWebRequest $request)
  {
	  $feed = new sfRssFeed();
	  $feed->setTitle('Les derniers mots ajoutés');
	  $feed->setLink('http://explications-informatiques.fr');
	  $feed->setAuthorEmail('contact@explications-informatiques.fr');
	  $feed->setAuthorName('Explications Informatiques');
	
	 
	
	  $q = Doctrine_Query::create()
	 	->from('lexiquemot')
		->orderBy("idmots DESC")
	    ->limit(15);
	  $posts = $q->execute();
	
	  foreach ($posts as $post)
	  {
		$item = new sfFeedItem();
		$item->setTitle($post["mot"]);
		$item->setLink("search/lexique?id=".$post["idlexique_mot"]);
		$item->setPubdate(date("U",strtotime($post["date_ajout"],time())));
		$item->setUniqueId($post["idlexique_mot"]);
		$feed->addItem($item);
	  }
	
	  $this->feed = $feed;
  }
  public function executeAtom(sfWebRequest $request)
  {
	  $feed = new sfAtom1Feed();
	  $feed->setTitle('Les derniers mots ajoutés');
	  $feed->setLink('http://explications-informatiques.fr');
	  $feed->setAuthorEmail('contact@explications-informatiques.fr');
	  $feed->setAuthorName('Explications Informatiques');
	
	 
	
	  $q = Doctrine_Query::create()
	 	->from('lexiquemot')
		->orderBy("idmots DESC")
	    ->limit(15);
	  $posts = $q->execute();
	
	  foreach ($posts as $post)
	  {
		$item = new sfFeedItem();
		$item->setTitle($post["mot"]);
		$item->setLink("search/lexique?id=".$post["idlexique_mot"]);
		$item->setPubdate(date("U",strtotime($post["date_ajout"],time())));
		$item->setUniqueId($post["idlexique_mot"]);
	
		$feed->addItem($item);
	  }
	
	  $this->feed = $feed;
  }
}
